package com.kiss.rpc.protection;

import java.util.concurrent.atomic.AtomicInteger;

public class CircuitBreaker {

    private volatile boolean isOpen = false;

    private final AtomicInteger requestCount = new AtomicInteger(0);

    private final AtomicInteger errorRequest = new AtomicInteger(0);

    private final int maxErrorRequest;
    private final float maxErrorRate;

    public CircuitBreaker(int maxErrorRequest, float maxErrorRate) {
        this.maxErrorRate = maxErrorRate;
        this.maxErrorRequest = maxErrorRequest;
    }

    public boolean isBreak() {
        if (isOpen) {
            return true;
        }

        if (errorRequest.get() > maxErrorRequest) {
            this.isOpen = true;
            return true;
        }

        if ( errorRequest.get() > 0 && requestCount.get() > 0 &&
        errorRequest.get() / (float)requestCount.get() > maxErrorRate) {
            this.isOpen = true;
            return true;
        }

        return false;
    }

    public void recordRequest() {
        requestCount.incrementAndGet();
    }

    public void recordErrorRequest() {
        errorRequest.incrementAndGet();
    }

    public void reset() {
        this.isOpen = false;
        requestCount.set(0);
        errorRequest.set(0);
    }
}
